﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using AliCMS;
using System.Reflection;
using System.Net;
using System.Web.Script.Serialization;
using System.Threading;

namespace AliCMS.CourseModule.Bll
{
	public partial class Order : DbObjectBase, IOrder
	{
		public Order(int instanceID, string lang, bool checkRight, string database)
			: base(instanceID, lang, checkRight, database)
		{
		}

		public override object ExecuteService(HttpContext context)
		{
			object result = null;

			string operation = context.Request.QueryString["Operation"];
			if (operation == "Add")
			{
				Dictionary<string, object> item = new Dictionary<string, object>();
				string value = null;
				value = context.Request.Form["No"];
				if (value != null) item[Alias.Order.No] = value;
				value = context.Request.Form["CourseID"];
				if (value != null) item[Alias.Order.CourseID] = value;
				value = context.Request.Form["CourseName"];
				if (value != null) item[Alias.Order.CourseName] = value;
				value = context.Request.Form["CourseThumbnail"];
				if (value != null) item[Alias.Order.CourseThumbnail] = value;
				value = context.Request.Form["TimeUnit"];
				if (value != null) item[Alias.Order.TimeUnit] = value;
				value = context.Request.Form["TimeAmount"];
				if (value != null) item[Alias.Order.TimeAmount] = value;
				value = context.Request.Form["UserID"];
				if (value != null) item[Alias.Order.UserID] = value;
				value = context.Request.Form["UserName"];
				if (value != null) item[Alias.Order.UserName] = value;
				value = context.Request.Form["UserNickname"];
				if (value != null) item[Alias.Order.UserNickname] = value;
				value = context.Request.Form["UserHead"];
				if (value != null) item[Alias.Order.UserHead] = value;
				value = context.Request.Form["TeacherID"];
				if (value != null) item[Alias.Order.TeacherID] = value;
				value = context.Request.Form["TeacherName"];
				if (value != null) item[Alias.Order.TeacherName] = value;
				value = context.Request.Form["TeacherHead"];
				if (value != null) item[Alias.Order.TeacherHead] = value;
				value = context.Request.Form["TeacherCommision"];
				if (value != null) item[Alias.Order.TeacherCommision] = value;
				value = context.Request.Form["DistributerID"];
				if (value != null) item[Alias.Order.DistributerID] = value;
				value = context.Request.Form["DistributerName"];
				if (value != null) item[Alias.Order.DistributerName] = value;
				value = context.Request.Form["DistributerNickname"];
				if (value != null) item[Alias.Order.DistributerNickname] = value;
				value = context.Request.Form["DistributerHead"];
				if (value != null) item[Alias.Order.DistributerHead] = value;
				value = context.Request.Form["DistributerIsAgent"];
				if (value != null) item[Alias.Order.DistributerIsAgent] = value;
				value = context.Request.Form["AgentCommision"];
				if (value != null) item[Alias.Order.AgentCommision] = value;
				value = context.Request.Form["Promotion"];
				if (value != null) item[Alias.Order.Promotion] = value;
				value = context.Request.Form["Price"];
				if (value != null) item[Alias.Order.Price] = value;
				value = context.Request.Form["Sum"];
				if (value != null) item[Alias.Order.Sum] = value;
				value = context.Request.Form["PaymentID"];
				if (value != null) item[Alias.Order.PaymentID] = value;
				value = context.Request.Form["PaymentName"];
				if (value != null) item[Alias.Order.PaymentName] = value;
				value = context.Request.Form["PaymentType"];
				if (value != null) item[Alias.Order.PaymentType] = value;
				value = context.Request.Form["PaymentAccountName"];
				if (value != null) item[Alias.Order.PaymentAccountName] = value;
				value = context.Request.Form["PaymentAccountNo"];
				if (value != null) item[Alias.Order.PaymentAccountNo] = value;
				value = context.Request.Form["CreatorName"];
				if (value != null) item[Alias.Order.CreatorName] = value;
				value = context.Request.Form["CreatorID"];
				if (value != null) item[Alias.Order.CreatorID] = value;
				value = context.Request.Form["CreateTime"];
				if (value != null) item[Alias.Order.CreateTime] = value;

				result = Add(item);
			}
			else if (operation == "Modify")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> changes = new Dictionary<string, object>();
				string value = null;
				value = context.Request.Form["PaymentID"];
				if (value != null) changes[Alias.Order.PaymentID] = value;
				value = context.Request.Form["PaymentName"];
				if (value != null) changes[Alias.Order.PaymentName] = value;
				value = context.Request.Form["PaymentType"];
				if (value != null) changes[Alias.Order.PaymentType] = value;
				value = context.Request.Form["PaymentAccountName"];
				if (value != null) changes[Alias.Order.PaymentAccountName] = value;
				value = context.Request.Form["PaymentAccountNo"];
				if (value != null) changes[Alias.Order.PaymentAccountNo] = value;

				Modify(id, changes);
			}
			else if (operation == "Delete")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Delete(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "List")
			{
				string value = null;

				int page = -1;
				value = context.Request.QueryString["Page"];
				if (value != null) page = Convert.ToInt32(value);

				int pageSize = -1;
				value = context.Request.QueryString["PageSize"];
				if (value != null) pageSize = Convert.ToInt32(value);

				string condition = context.Request.QueryString["Condition"];
				string sort = context.Request.QueryString["Sort"];

				result = List(page, pageSize, condition, sort);
			}
			else if (operation == "Pay")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;

				//Amount
				value = context.Request.Form["Amount"];
				if (value != null && !String.IsNullOrEmpty(value))
					data["Amount"] = Convert.ToDecimal(value);

				//PayTime
				value = context.Request.Form["PayTime"];
				if (value != null && !String.IsNullOrEmpty(value))
					data["PayTime"] = Convert.ToDateTime(value);
				else
					data["PayTime"] = DateTime.Now;

				//PayMemo
				value = context.Request.Form["PayMemo"];
				if (value != null)
					data["PayMemo"] = value;
				else
					data["PayMemo"] = DBNull.Value;

				//PaymentID
				value = context.Request.Form["PaymentID"];
				if (!String.IsNullOrEmpty(value))
					data["PaymentID"] = new Guid(value);
				else
					data["PaymentID"] = DBNull.Value;

				//PaymentName
				value = context.Request.Form["PaymentName"];
				if (value != null)
					data["PaymentName"] = value;
				else
					data["PaymentName"] = DBNull.Value;

				//PaymentType
				value = context.Request.Form["PaymentType"];
				if (value != null)
					data["PaymentType"] = value;
				else
					data["PaymentType"] = DBNull.Value;

				//PaymentAccountName
				value = context.Request.Form["PaymentAccountName"];
				if (value != null)
					data["PaymentAccountName"] = value;
				else
					data["PaymentAccountName"] = DBNull.Value;

				//PaymentAccount
				value = context.Request.Form["PaymentAccountNo"];
				if (value != null)
					data["PaymentAccountNo"] = value;
				else
					data["PaymentAccountNo"] = DBNull.Value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				//
				Pay(id, data);
			}
			else if (operation == "Refund")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;

				//Amount
				value = context.Request.Form["Amount"];
				if (value != null && !String.IsNullOrEmpty(value))
					data["Amount"] = Convert.ToDecimal(value);

				//RefundTime
				value = context.Request.Form["RefundTime"];
				if (value != null && !String.IsNullOrEmpty(value))
					data["RefundTime"] = Convert.ToDateTime(value);
				else
					data["RefundTime"] = DateTime.Now;

				//RefundMemo
				value = context.Request.Form["RefundMemo"];
				if (value != null)
					data["RefundMemo"] = value;
				else
					data["RefundMemo"] = DBNull.Value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				Refund(id, data);
			}
			else if (operation == "Deliver")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;
				value = context.Request.Form["DeliverTime"];
				if (value != null)
					data[Alias.Order.DeliverTime] = Convert.ToDateTime(value);
				else
					data[Alias.Order.DeliverTime] = DateTime.Now;
				value = context.Request.Form["DeliverMemo"];
				if (value != null) data[Alias.Order.DeliverMemo] = value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				Deliver(id, data);
			}
			else if (operation == "Return")
			{
				int id = Convert.ToInt32(context.Request.QueryString["ID"]);

				Dictionary<string, object> data = new Dictionary<string, object>();
				string value = null;
				value = context.Request.Form["ReturnTime"];
				if (value != null)
					data[Alias.Order.ReturnTime] = Convert.ToDateTime(value);
				else
					data[Alias.Order.ReturnTime] = DateTime.Now;
				value = context.Request.Form["ReturnMemo"];
				if (value != null)
					data[Alias.Order.ReturnMemo] = value;
				else
					data[Alias.Order.ReturnMemo] = DBNull.Value;

				//从app调用时，发来的当前用户ID
				data["CurUserID"] = context.Request.Form["CurUserID"];
				data["CurUserName"] = context.Request.Form["CurUserName"];

				Return(id, data);
			}
			else if (operation == "Finish")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Finish(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "Cancel")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Cancel(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "Archive")
			{
				string id = context.Request.QueryString["ID"];

				string[] ids = id.Split('|');
				for (int i = 0; i < ids.Length; i++)
				{
					if (String.IsNullOrEmpty(ids[i]))
						continue;

					Archive(Convert.ToInt32(ids[i]));
				}
			}
			else if (operation == "Get")
			{
				object id = null;
				if (Regex.IsMatch(context.Request.QueryString["ID"], @"^\d+$"))
					id = Convert.ToInt32(context.Request.QueryString["ID"]);
				else
					id = new Guid(context.Request.QueryString["ID"]);
				result = Get(id);
			}
			else if (operation == "OnlinePayRequest")
			{
				result = OnlinePayRequest(new Guid(context.Request.QueryString["ID"]));
			}
			else if (operation == "OnlinePayNotify")
			{
				#region 调试
				//string allKeys = "";
				//SortedDictionary<string, string> keys = Alipay_GetHttpString();
				//foreach (KeyValuePair<string, string> kvp in keys)
				//{
				//    allKeys += "\r\n" + kvp.Key + "=" + kvp.Value;
				//}
				//File.AppendAllText(Manager.MapPath("/log_payment.txt"), allKeys);
				#endregion

				result = OnlinePayNotify();
			}
			else if (operation == "GetInnerIDFromGuid")
			{
				Guid guid = new Guid(context.Request.QueryString["ID"]);
				result = GetInnerIDFromGuid(guid);
			}
            #region 统计
            else if (operation == "Stat")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Stat(data);
            }
            else if (operation == "StatHourly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = StatHourly(data);
            }
            else if (operation == "StatDaily")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = StatDaily(data);
            }
            else if (operation == "StatMonthly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = StatMonthly(data);
            }
            #endregion
            #region 教师统计
            else if (operation == "Teacher_StatOne")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Teacher_StatOne(new Guid(context.Request.QueryString["TeacherID"]), data);
            }
            else if (operation == "Teacher_StatAll")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Teacher_StatAll(data);
            }
            else if (operation == "Teacher_StatHourly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Teacher_StatHourly(new Guid(context.Request.QueryString["TeacherID"]), data);
            }
            else if (operation == "Teacher_StatDaily")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Teacher_StatDaily(new Guid(context.Request.QueryString["TeacherID"]), data);
            }
            else if (operation == "Teacher_StatMonthly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Teacher_StatMonthly(new Guid(context.Request.QueryString["TeacherID"]), data);
            }
            #endregion
            #region 课程统计
            else if (operation == "Course_StatOne")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Course_StatOne(new Guid(context.Request.QueryString["CourseID"]), data);
            }
            else if (operation == "Course_StatAll")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Course_StatAll(data);
            }
            else if (operation == "Course_StatHourly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Course_StatHourly(new Guid(context.Request.QueryString["CourseID"]), data);
            }
            else if (operation == "Course_StatDaily")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Course_StatDaily(new Guid(context.Request.QueryString["CourseID"]), data);
            }
            else if (operation == "Course_StatMonthly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;

                result = Course_StatMonthly(new Guid(context.Request.QueryString["CourseID"]), data);
            }
            #endregion
            #region 代理统计
            else if (operation == "Agent_StatOne")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatOne(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            else if (operation == "Agent_StatAll")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatAll(data);
            }
            else if (operation == "Agent_StatHourly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatHourly(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            else if (operation == "Agent_StatDaily")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatDaily(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            else if (operation == "Agent_StatMonthly")
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                string value = null;
                value = context.Request.QueryString["Start"];
                if (value != null) data["Start"] = value;
                value = context.Request.QueryString["End"];
                if (value != null) data["End"] = value;
                value = context.Request.QueryString["IsFinished"];
                if (value != null) data["IsFinished"] = value;
                value = context.Request.QueryString["IsArchived"];
                if (value != null) data["IsArchived"] = value;
                value = context.Request.QueryString["IsCanceled"];
                if (value != null) data["IsCanceled"] = value;
                value = context.Request.QueryString["IsPayed"];
                if (value != null) data["IsPayed"] = value;
                value = context.Request.QueryString["IsDelivered"];
                if (value != null) data["IsDelivered"] = value;
                value = context.Request.QueryString["Depth"];
                if (value != null) data["Depth"] = value;

                result = Agent_StatMonthly(new Guid(context.Request.QueryString["AgentID"]), data);
            }
            #endregion
            else
            {
				throw new Exception("lang_header_param");
			}

			return result;
		}

		public int GetInnerIDFromGuid(Guid guid)
		{
			return Dal.GetInnerIDFromGuid(guid);
		}
		public Guid GetGuidFromInnerID(object id)
		{
			return Dal.GetGuidFromInnerID(id);
		}
		public Dictionary<string, object> Get(object id)
		{
			if (CheckRight)
			{
				Guid guid;
				if (id is Guid)
					guid = (Guid)id;
				else
					guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Get", guid);
			}

			return Dal.Get(id);
		}
		public Guid Add(Dictionary<string, object> item)
		{
			if (CheckRight)
			{
				ValidateRight("Add", Guid.Empty);
			}

			if (!item.ContainsKey(Alias.Order.ID) || item[Alias.Order.ID].ToString() == String.Empty)
				item[Alias.Order.ID] = Guid.NewGuid();
			else if (!(item[Alias.Order.ID] is Guid))
				item[Alias.Order.ID] = new Guid(item[Alias.Order.ID].ToString());

			if (!item.ContainsKey(Alias.Order.No) || String.IsNullOrEmpty(Convert.ToString(item[Alias.Order.No])))
				item[Alias.Order.No] = DateTime.Now.ToString("yyyyMMddHHmmss");

			if (item.ContainsKey(Alias.Order.CourseID))
			{
				string courseId = item[Alias.Order.CourseID].ToString();
				if (courseId == String.Empty || courseId == Guid.Empty.ToString())
					item[Alias.Order.CourseID] = DBNull.Value;
				else
					item[Alias.Order.CourseID] = new Guid(courseId);
			}

			if (item.ContainsKey(Alias.Order.UserID))
			{
				string userId = item[Alias.Order.UserID].ToString();
				if (userId == String.Empty || userId == Guid.Empty.ToString())
					item[Alias.Order.UserID] = DBNull.Value;
				else
					item[Alias.Order.UserID] = new Guid(userId);
			}

			if (item.ContainsKey(Alias.Order.TeacherID))
			{
				string teacherId = item[Alias.Order.TeacherID].ToString();
				if (teacherId == String.Empty || teacherId == Guid.Empty.ToString())
					item[Alias.Order.TeacherID] = DBNull.Value;
				else
					item[Alias.Order.TeacherID] = new Guid(teacherId);
			}

			if (item.ContainsKey(Alias.Order.DistributerID))
			{
				string distributerId = item[Alias.Order.DistributerID].ToString();
				if (distributerId == String.Empty || distributerId == Guid.Empty.ToString())
					item[Alias.Order.DistributerID] = DBNull.Value;
				else
					item[Alias.Order.DistributerID] = new Guid(distributerId);
			}

			if (item.ContainsKey(Alias.Order.PaymentID))
			{
				string paymentId = item[Alias.Order.PaymentID].ToString();
				if (paymentId == String.Empty || paymentId == Guid.Empty.ToString())
					item[Alias.Order.PaymentID] = DBNull.Value;
				else
					item[Alias.Order.PaymentID] = new Guid(paymentId);
			}

			//用户
			Dictionary<string, string> user = Manager.User;
			if (!item.ContainsKey(Alias.Order.UserID) && user != null)
			{
				item[Alias.Order.UserName] = user["Name"];
				item[Alias.Order.UserID] = new Guid(user["ID"]);
			}

			//创建人
			if (item.ContainsKey(Alias.Order.CreatorID) && !String.IsNullOrEmpty(Convert.ToString(item[Alias.Order.CreatorID])))
			{
				item[Alias.Order.CreatorID] = new Guid(item[Alias.Order.CreatorID].ToString());
			}
			else
			{
				if (user != null)
				{
					item[Alias.Order.CreatorName] = user["Name"];
					item[Alias.Order.CreatorID] = new Guid(user["ID"]);
				}
			}

			Dal.Add(item);

            return (Guid)item[Alias.Order.ID];
		}
		public void Modify(int id, Dictionary<string, object> changes)
		{
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Modify", guid);
			}

			if (changes.ContainsKey(Alias.Order.PaymentID))
			{
				string paymentId = changes[Alias.Order.PaymentID].ToString();
				if (paymentId == String.Empty || paymentId == Guid.Empty.ToString())
					changes[Alias.Order.PaymentID] = DBNull.Value;
				else
					changes[Alias.Order.PaymentID] = new Guid(paymentId);
			}

			Dal.Modify(id, changes);
		}
		public void Delete(int id)
		{
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Delete", guid);
			}

			Dal.Delete(id);
		}
		public DataTable List(int page, int pageSize, string condition, string sort)
		{
			if (CheckRight)
			{
				ValidateRight("List", Guid.Empty);
			}

			return Dal.List(page, pageSize, condition, sort);
		}
		public int GetRecordCount(string condition)
		{
			return Dal.GetRecordCount(condition);
		}

		public void Pay(int id, Dictionary<string, object> data)
		{
			Dictionary<string, object> order = Dal.Get(id);

			if (CheckRight)
			{
				//Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Pay", (Guid)order[Alias.Order.ID]);
			}

			#region 权限
			String curUserId = Convert.ToString(data["CurUserID"]);
			String curUserName = Convert.ToString(data["CurUserName"]);
			if (String.IsNullOrEmpty(curUserId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
				{
					Exception exp = new Exception("lang_no_right");
					throw exp;
				}
				curUserId = user["ID"];
				curUserName = user["Name"];
			}
			#endregion

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.PayTime] = data["PayTime"];
			changes[Alias.Order.PayMemo] = data["PayMemo"];
			changes[Alias.Order.PaymentID] = data["PaymentID"];
			changes[Alias.Order.PaymentName] = data["PaymentName"];
			changes[Alias.Order.PaymentType] = data["PaymentType"];
			changes[Alias.Order.PaymentAccountName] = data["PaymentAccountName"];
			changes[Alias.Order.PaymentAccountNo] = data["PaymentAccountNo"];
			changes[Alias.Order.PayOperatorID] = new Guid(curUserId);
			changes[Alias.Order.PayOperatorName] = curUserName;
			changes[Alias.Order.IsPayed] = 2;

			Dal.Modify(id, changes);
			#endregion

			//支付后处理
			OnAfterPay(order);
		}
		public void Refund(int id, Dictionary<string, object> data)
		{
			Dictionary<string, object> order = Dal.Get(id);
			if (CheckRight)
			{
				ValidateRight("Refund", (Guid)order[Alias.Order.ID]);
			}

			#region 权限
			String curUserId = Convert.ToString(data["CurUserID"]);
			String curUserName = Convert.ToString(data["CurUserName"]);
			if (String.IsNullOrEmpty(curUserId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
				{
					Exception exp = new Exception("lang_no_right");
					throw exp;
				}
				curUserId = user["ID"];
				curUserName = user["Name"];
			}
			#endregion

			decimal sum = Convert.ToDecimal(order[Alias.Order.Sum]);
			decimal amount;
			if (data.ContainsKey("Amount"))
				amount = Convert.ToDecimal(data["Amount"]);
			else
				amount = sum;

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.RefundTime] = data["RefundTime"];
			changes[Alias.Order.RefundMemo] = data["RefundMemo"];
			changes[Alias.Order.RefundAmount] = amount;
			changes[Alias.Order.RefundOperatorID] = new Guid(curUserId);
			changes[Alias.Order.RefundOperatorName] = curUserName;
			if (amount == sum)
				changes[Alias.Order.IsPayed] = 4;
			else
				changes[Alias.Order.IsPayed] = 3;

			Dal.Modify(id, changes);
			#endregion

			//退款后处理
			OnAfterRefund(order);
		}
		public void Deliver(int id, Dictionary<string, object> data)
		{
			Dictionary<string, object> order = Dal.Get(id);
			if (CheckRight)
			{
				ValidateRight("Deliver", (Guid)order[Alias.Order.ID]);
			}

			#region 权限
			String curUserId = Convert.ToString(data["CurUserID"]);
			String curUserName = Convert.ToString(data["CurUserName"]);
			if (String.IsNullOrEmpty(curUserId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
				{
					Exception exp = new Exception("lang_no_right");
					throw exp;
				}
				curUserId = user["ID"];
				curUserName = user["Name"];
			}
			#endregion

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.DeliverTime] = data[Alias.Order.DeliverTime];
			if (data.ContainsKey(Alias.Order.DeliverMemo))
				changes[Alias.Order.DeliverMemo] = data[Alias.Order.DeliverMemo];
			changes[Alias.Order.IsDelivered] = 2;

			int amount = Convert.ToInt32(order[Alias.Order.TimeAmount]);
			DateTime deliverTime = (DateTime)data[Alias.Order.DeliverTime];
			switch (order[Alias.Order.TimeUnit].ToString())
			{
				case "MONTH":
					changes[Alias.Order.ExpiredTime] = deliverTime.AddMonths(amount);
					break;
				case "SEASON":
					changes[Alias.Order.ExpiredTime] = deliverTime.AddMonths(3 * amount);
					break;
				case "HAFE_YEAR":
					changes[Alias.Order.ExpiredTime] = deliverTime.AddMonths(6 * amount);
					break;
				case "YEAR":
					changes[Alias.Order.ExpiredTime] = deliverTime.AddYears(amount);
					break;
			}

			changes[Alias.Order.DeliverOperatorID] = new Guid(curUserId);
			changes[Alias.Order.DeliverOperatorName] = curUserName;

			Dal.Modify(id, changes);
			#endregion

			//支付后处理
			OnAfterDeliver(order);
		}
		public void Return(int id, Dictionary<string, object> data)
		{
			Dictionary<string, object> order = Dal.Get(id);
			if (CheckRight)
			{
				ValidateRight("Deliver", (Guid)order[Alias.Order.ID]);
			}

			#region 权限
			String curUserId = Convert.ToString(data["CurUserID"]);
			String curUserName = Convert.ToString(data["CurUserName"]);
			if (String.IsNullOrEmpty(curUserId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
				{
					Exception exp = new Exception("lang_no_right");
					throw exp;
				}
				curUserId = user["ID"];
				curUserName = user["Name"];
			}
			#endregion

			#region 设置状态
			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.IsDelivered] = 3;
			changes[Alias.Order.ReturnTime] = data[Alias.Order.ReturnTime];
			changes[Alias.Order.ReturnMemo] = data[Alias.Order.ReturnMemo];
			changes[Alias.Order.ReturnOperatorID] = new Guid(curUserId);
			changes[Alias.Order.ReturnOperatorName] = curUserName;

			Dal.Modify(id, changes);
			#endregion

			#region 删除“正在学习”
			using (ICourseStudy bll = (ICourseStudy)Manager.CreateObject("CourseStudy", InstanceID, Lang, false))
			{
				DataTable table = bll.List(-1, -1, Alias.CourseStudy.CourseID + "=" + order[Alias.Order.CourseID], null);
				foreach (DataRow row in table.Rows)
                {
					bll.Delete(Convert.ToInt32(row[Alias.CourseStudy.InnerID]));
                }
			}
			#endregion
		}
		public void Finish(int id)
		{
			if (CheckRight)
			{
			    Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Finish", guid);
			}

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.IsFinished] = true;
			Dal.Modify(id, changes);
		}
		public void Cancel(int id)
		{
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Cancel", guid);
			}

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.IsCanceled] = true;

			Dal.Modify(id, changes);
		}
		public void Archive(int id)
		{
			if (CheckRight)
			{
				Guid guid = Dal.GetGuidFromInnerID(id);
				ValidateRight("Archive", guid);
			}

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.IsArchived] = true;

			Dal.Modify(id, changes);
		}

		/*
		** 作用：构造跳转表单。 
		** 注释：（1）用户要登录状态。
		**		 （2）以post方式提交数据。
		**		 （3）必须提交的数据：Title，PaymentID，Amount，ReturnUrl
		**		 （4）支付宝网银接口还需提交：DefaultBank
		**/
		public object OnlinePayRequest(Guid orderId)
		{
			HttpRequest request = HttpContext.Current.Request;
			String userId = request.Form["UserID"];
			if (String.IsNullOrEmpty(userId))
			{
				Dictionary<string, string> user = Manager.User;
				if (user == null)
					return null;

				userId = user["ID"];
			}

			#region 必须设置RechargeNotifyUrl
			Dictionary<string, string> instanceConfig = null;
			using (IInstanceConfig bll = (IInstanceConfig)Manager.CreateObject("InstanceConfig", InstanceID, Lang, false))
			{
				instanceConfig = bll.GetBasicSettings();
			}

			string notifyUrl = instanceConfig[Alias.InstanceConfig.OnlinePayNotifyUrl].ToString();
			if (String.IsNullOrEmpty(notifyUrl))
				return null;
			#endregion

			#region 获取支付方式
			Dictionary<string, object> payment = null;
			using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
			{
				payment = paymentBll.Get(new Guid(request.Form["PaymentID"]));
			}
			#endregion

			#region 只允许在线支付
			if (!Convert.ToBoolean(payment[SystemModule.Alias.Payment.IsOnline]))
				return null;
			#endregion

			#region 修改订单支付信息
			Guid outTradeNo = orderId;

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.PaymentID] = new Guid(request.Form["PaymentID"]);
			changes[Alias.Order.PaymentName] = payment[SystemModule.Alias.Payment.Name];
			changes[Alias.Order.PaymentType] = payment[SystemModule.Alias.Payment.Type];
			changes[Alias.Order.PaymentAccountName] = payment[SystemModule.Alias.Payment.AccountName];
			if (payment[SystemModule.Alias.Payment.Type].ToString().Contains("WEIXIN"))
				changes[Alias.Order.PaymentAccountNo] = payment[SystemModule.Alias.Payment.PartnerID];
			else
				changes[Alias.Order.PaymentAccountNo] = payment[SystemModule.Alias.Payment.Account];
			Dal.CheckRight = false;
			Dal.Modify(GetInnerIDFromGuid(orderId), changes);
			#endregion

			string type = payment[SystemModule.Alias.Payment.Type].ToString();
			string action = String.Empty;
			string method = String.Empty;
			SortedDictionary<string, string> array = new SortedDictionary<string, string>();
			if (type == "CHINA_BANK")//网银在线
			{
				action = "https://pay3.chinabank.com.cn/PayGate";
				method = "post";

				#region v_md5info
				string text = request["Amount"] + "CNY" + outTradeNo + payment[SystemModule.Alias.Payment.PartnerID] + request["ReturnUrl"] + payment[SystemModule.Alias.Payment.Key]; // 拼凑加密串
				string md5info = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "md5").ToUpper();
				#endregion

				#region 构造参数
				array["v_md5info"] = md5info;
				array["v_mid"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
				array["v_oid"] = outTradeNo.ToString();
				array["v_amount"] = request["Amount"];
				array["v_moneytype"] = "CNY";
				array["v_url"] = request["ReturnUrl"].ToString();
				array["remark1"] = request["remark1"];
				array["remark2"] = "[url:=" + notifyUrl + "]";
				array["v_rcvname"] = request["v_rcvname"];
				array["v_rcvaddr"] = request["v_rcvaddr"];
				array["v_rcvtel"] = request["v_rcvtel"];
				array["v_rcvpost"] = request["v_rcvpost"];
				array["v_rcvemail"] = request["v_rcvemail"];
				array["v_rcvmobile"] = request["v_rcvmobile"];
				array["v_ordername"] = request["v_ordername"];
				array["v_orderaddr"] = request["v_orderaddr"];
				array["v_ordertel"] = request["v_ordertel"];
				array["v_orderpost"] = request["v_orderpost"];
				array["v_orderemail"] = request["v_orderemail"];
				array["v_ordermobile"] = request["v_ordermobile"];
				#endregion
			}
			else if (type == "WEIXIN_PAY_BY_WAP")//微信支付（网页接口）
			{
				action = request["ReturnUrl"];
				method = "get";

				#region 构造参数
				array["ID"] = outTradeNo.ToString();
				array["Title"] = request.Form["Title"];
				array["PaymentType"] = payment[SystemModule.Alias.Payment.Type].ToString();
				array["PaymentID"] = request.Form["PaymentID"];
				array["Amount"] = request.Form["Amount"];
				array["NotifyUrl"] = notifyUrl;
				#endregion
			}
			else if (type == "WEIXIN_PAY_BY_APP")
			{
				#region 准备配置
				Dictionary<string, string> config = new Dictionary<string, string>();
				config["APPID"] = payment[SystemModule.Alias.Payment.AccountName].ToString();
				config["MCHID"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
				config["KEY"] = payment[SystemModule.Alias.Payment.Key].ToString();
				config["APPSECRET"] = payment[SystemModule.Alias.Payment.Account].ToString();
				#endregion

				#region 准备数据
				WxPayApi.PayData data = new WxPayApi.PayData(config);
				data.SetValue("appid", config["APPID"]);
				data.SetValue("mch_id", config["MCHID"]);
				data.SetValue("device_info", "WEB");
				data.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));
				data.SetValue("body", outTradeNo.ToString());
				data.SetValue("out_trade_no", outTradeNo.ToString().Replace("-", ""));
				data.SetValue("total_fee", Convert.ToString(Convert.ToInt32(Convert.ToDecimal(request.Form["Amount"]) * 100)));
				data.SetValue("spbill_create_ip", request.UserHostAddress);
				data.SetValue("notify_url", notifyUrl);
				data.SetValue("trade_type", "APP");
				data.SetValue("sign", data.MakeSign());
				#endregion

				#region 请求Url
				String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
				HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
				req.Method = "POST";
				req.Timeout = 15 * 1000;
				req.ContentType = "text/xml";
				byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data.ToXml());
				req.ContentLength = buffer.Length;
				#endregion

				#region 往服务器写入数据
				Stream reqStream = req.GetRequestStream();
				reqStream.Write(buffer, 0, buffer.Length);
				reqStream.Close();
				#endregion

				#region 获取服务端返回
				HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
				StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
				String orderResult = sr.ReadToEnd().Trim();
				sr.Close();

				//统一订单数据
				data.Clear();
				data.FromXml(orderResult);
				String returnCode = Convert.ToString(data.GetValue("return_code"));
				String prepayId = Convert.ToString(data.GetValue("prepay_id"));

				//生成支付参数
				if (returnCode == "SUCCESS")
				{
					data.Clear();
					data.SetValue("appid", config["APPID"]);
					data.SetValue("partnerid", config["MCHID"]);
					data.SetValue("prepayid", prepayId);
					data.SetValue("package", "Sign=WXPay");
					data.SetValue("noncestr", Guid.NewGuid().ToString().Replace("-", ""));
					data.SetValue("timestamp", WxPayApi.PrepareParam.GenerateTimeStamp());
					data.SetValue("sign", data.MakeSign());

					return new Dictionary<string, object>(data.GetValues());
				}
				else
				{
					Manager.Log("GoodsModule.Bll.Order - OnlinePayRequest - 生成支付参数", orderResult, Lang);
					/*
					File.AppendAllText(Manager.MapPath("~/log.txt"), @"\r\n==========================  微信支付  =================================\r\n
																	日期：" + DateTime.Now + "\r\n" + orderResult +
																	 "\r\n=======================================================================\r\n");
					*/
					return null;
				}
				#endregion
			}
			else if (type == "ALIPAY_DIRECT_PAY_BY_APP")
			{
				Dictionary<String, String> orderMap = new Dictionary<string, string>();
				orderMap["app_id"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
				orderMap["biz_content"] = "{" +
												"\"subject\":\"" + request.Form["Title"] + "\"" +
												",\"seller_id\":\"\"" +
												",\"total_amount\":\"" + request.Form["Amount"] + "\"" +
												",\"product_code\":\"QUICK_MSECURITY_PAY\"" +
												",\"out_trade_no\":\"" + outTradeNo + "\"" +
											"}";
				orderMap["charset"] = "utf-8";
				orderMap["method"] = "alipay.trade.app.pay";
				orderMap["notify_url"] = notifyUrl;
				orderMap["sign_type"] = "RSA";
				orderMap["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
				orderMap["version"] = "1.0";

				//
				String orderString = "";
				String orderStringEncoded = "";
				foreach (KeyValuePair<String, String> kvp in orderMap)
				{
					if (orderString != "")
					{
						orderString += "&";
						orderStringEncoded += "&";
					}
					orderString += kvp.Key + "=" + kvp.Value;
					orderStringEncoded += kvp.Key + "=" + HttpUtility.UrlEncode(kvp.Value);
				}

				//签名
				String sign = HttpUtility.UrlEncodeUnicode(AliPayApi.RSA.sign(orderString, payment[SystemModule.Alias.Payment.Key].ToString(), "utf-8"));

				//
				orderStringEncoded += "&sign=" + sign;
				return orderStringEncoded;

				/*
				String orderString = "service=\"mobile.securitypay.pay\"";
				orderString += "&partner=\"" + payment[partnerIdField] + "\"";
				orderString += "&_input_charset=\"utf-8\"";
				orderString += "&notify_url=\"" + notifyUrl + "\"";
				orderString += "&out_trade_no=\"" + outTradeNo + "\"";
				orderString += "&subject=\"" + request.Form["Title"] + "\"";
				orderString += "&payment_type=\"1\"";
				orderString += "&seller_id=\"" + payment[partnerIdField] + "\"";
				orderString += "&total_fee=\"" + request.Form["Amount"] + "\"";
				orderString += "&body=\"" + request.Form["Title"] + "\"";
				//orderString += "&sign=\"" + HttpUtility.UrlEncodeUnicode(AliPayApi.RSAFromPkcs8.sign(orderString, payment[keyField].ToString(), "utf-8")) + "\"";
				orderString += "&sign=\"" + HttpUtility.UrlEncodeUnicode(AliPayApi.RSA.sign(orderString, payment[keyField].ToString(), "utf-8")) + "\"";
				orderString += "&sign_type=\"RSA\"";

				return orderString;
				*/
			}
			else//默认为支付宝
			{
				AliPayApi.AliPayApi aliPayApi = new AliPayApi.AliPayApi();

				string charset = "utf-8";
				string signType = "MD5";
				action = "https://mapi.alipay.com/gateway.do?_input_charset=" + charset;
				method = "get";

				#region 构造参数
				if (type == "ALIPAY_DIRECT_PAY_BY_WAP")
				{
					array["partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
					array["seller_id"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
					array["_input_charset"] = charset;
					array["service"] = "alipay.wap.create.direct.pay.by.user";
					array["payment_type"] = "1";
					array["notify_url"] = notifyUrl;
					array["return_url"] = request.Form["ReturnUrl"];
					array["out_trade_no"] = outTradeNo.ToString();
					array["subject"] = request.Form["Title"];
					array["total_fee"] = request.Form["Amount"];
					array["show_url"] = HttpUtility.UrlEncode(request.Url.ToString());
					array["sign"] = aliPayApi.BuildMysign(array, payment[SystemModule.Alias.Payment.Key].ToString(), signType, charset);
					array["sign_type"] = signType;
				}
				else if (type == "ALIPAY_DIRECT_PAY_BY_BANK")
				{
					array["service"] = "create_direct_pay_by_user";
					array["paymethod"] = "bankPay";
					array["defaultbank"] = request.Form["DefaultBank"];
					array["partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
					array["key"] = payment[SystemModule.Alias.Payment.Key].ToString();
					array["seller_email"] = payment[SystemModule.Alias.Payment.Account].ToString();
					array["return_url"] = request.Form["ReturnUrl"];
					array["notify_url"] = notifyUrl;
					array["_input_charset"] = charset;
					array["subject"] = request.Form["Title"];
					array["price"] = request.Form["Amount"];
					array["body"] = request.Form["Title"];
					array["out_trade_no"] = outTradeNo.ToString();
					array["quantity"] = "1";
					array["payment_type"] = "1";
					array["logistics_fee"] = "0";
					array["logistics_payment"] = "SELLER_PAY";
					array["logistics_type"] = "EXPRESS";
					array["sign"] = aliPayApi.BuildMysign(array, payment[SystemModule.Alias.Payment.Key].ToString(), signType, charset);
					array["sign_type"] = signType;
				}
				else// if (type == "ALIPAY_DIRECT_PAY_BY_PC")
				{
					array["service"] = "create_direct_pay_by_user";
					array["partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
					array["key"] = payment[SystemModule.Alias.Payment.Key].ToString();
					array["seller_email"] = payment[SystemModule.Alias.Payment.Account].ToString();
					array["return_url"] = request.Form["ReturnUrl"];
					array["notify_url"] = notifyUrl;
					array["_input_charset"] = charset;
					array["subject"] = request.Form["Title"];
					array["price"] = request.Form["Amount"];
					array["body"] = request.Form["Title"];
					array["out_trade_no"] = outTradeNo.ToString();
					array["quantity"] = "1";
					array["payment_type"] = "1";
					array["logistics_fee"] = "0";
					array["logistics_payment"] = "SELLER_PAY";
					array["logistics_type"] = "EXPRESS";
					array["sign"] = aliPayApi.BuildMysign(array, payment[SystemModule.Alias.Payment.Key].ToString(), signType, charset);
					array["sign_type"] = signType;
				}
				#endregion
			}

			#region 表单
			StringBuilder result = new StringBuilder();
			result.Append("<form action=\"" + action + "\" method=\"" + method + "\">");
			foreach (KeyValuePair<string, string> param in array)
			{
				result.Append("<input type=\"hidden\" name=\"" + param.Key + "\" value=\"" + param.Value + "\">");
			}
			result.Append("</form>");
			return result.ToString();
			#endregion
		}
		private string OnlinePayNotify()
		{
			HttpRequest request = HttpContext.Current.Request;
			if (!String.IsNullOrEmpty(request["v_md5str"]))//网银在线
			{
				#region 获取并检查有没有参数
				string v_oid = request["v_oid"];
				string v_pstatus = request["v_pstatus"];
				string v_pstring = request["v_pstring"];
				string v_pmode = request["v_pmode"];
				string v_md5str = request["v_md5str"];
				string v_amount = request["v_amount"];
				string v_moneytype = request["v_moneytype"];
				string remark1 = request["remark1"];
				string remark2 = request["remark2"];
				#endregion

				#region 获取资金
				Dal.CheckRight = false;
				Dictionary<string, object> order = Dal.Get(new Guid(v_oid));

				if (order == null)
				{
					#region 调试
					//File.AppendAllText(logFile, "\r\nNo record!");
					#endregion

					return "error";
				}
				#endregion

				#region 获取支付方式
				Dictionary<string, object> payment = null;
				using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
				{
					payment = paymentBll.Get((Guid)order[Alias.Order.PaymentID]);
				}

				if (payment == null)
				{
					#region 调试
					//File.AppendAllText(logFile, "\r\nNo payment!");
					#endregion

					return "error";
				}
				#endregion

				#region 检查是否合法
				string str = v_oid + v_pstatus + v_amount + v_moneytype + payment[SystemModule.Alias.Payment.Key].ToString();
				str = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5").ToUpper();
				if (str != v_md5str)
					return "error";
				#endregion

				#region 如果成功，修改状态
				if (v_pstatus.Equals("20"))
				{
					OnlinePay(order, "", Convert.ToDecimal(v_amount));
				}

				return "ok";
				#endregion
			}
			else if (!String.IsNullOrEmpty(request["trade_status"]))//支付宝
			{
				AliPayApi.AliPayApi aliPayApi = new AliPayApi.AliPayApi();

				#region 获取并检查有没有参数
				SortedDictionary<string, string> array = aliPayApi.GetHttpString();
				array.Remove("Operation");
				array.Remove("Lang");
				if (array.Count == 0)
				{
					#region 调试
					//File.AppendAllText(logFile, "\r\nParameter error!");
					#endregion

					return "Parameter error!";
				}
				#endregion

				#region 获取资金
				Dal.CheckRight = false;
				Dictionary<string, object> order = Dal.Get(new Guid(array["out_trade_no"]));

				if (order == null)
				{
					#region 调试
					//File.AppendAllText(logFile, "\r\nNo record!");
					#endregion

					return "No record!";
				}
				#endregion

				#region 获取支付方式
				Dictionary<string, object> payment = null;
				using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
				{
					payment = paymentBll.Get((Guid)order[Alias.Order.PaymentID]);
				}

				if (payment == null)
				{
					#region 调试
					//File.AppendAllText(logFile, "\r\nNo payment!");
					#endregion

					return "No payment!";
				}
				#endregion

				if (payment[SystemModule.Alias.Payment.Type].ToString() == "ALIPAY_DIRECT_PAY_BY_APP")//app支付
				{
					#region 检查是否合法
					Dictionary<string, string> config = new Dictionary<string, string>();
					config["PublicKey"] = payment[SystemModule.Alias.Payment.AliPayPublicKey].ToString();
					config["SignType"] = array["sign_type"];
					config["Charset"] = "utf-8";

					bool isLegal = aliPayApi.GetSignVeryfy(config, array, array["sign"]);
					if (!isLegal)
					{
						#region 调试
						//File.AppendAllText(Manager.MapPath("/log.txt"), "\r\nVerify fail!");
						#endregion

						return "Verify fail!";
					}
					#endregion
				}
				else
				{
					#region 检查是否合法
					Dictionary<string, string> config = new Dictionary<string, string>();
					config["Key"] = payment[SystemModule.Alias.Payment.Key].ToString();
					config["Partner"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
					config["PublicKey"] = payment[SystemModule.Alias.Payment.AliPayPublicKey].ToString();
					config["SignType"] = array["sign_type"];
					config["Charset"] = "utf-8";

					bool isLegal = aliPayApi.Verify(config, array, array["notify_id"], array["sign"]);
					if (!isLegal)
					{
						#region 调试
						//File.AppendAllText(logFile, "\r\nVerify fail!");
						#endregion

						return "Verify fail!";
					}
					#endregion
				}

				#region 如果成功，修改状态
				if (array["trade_status"] == "TRADE_FINISHED" || array["trade_status"] == "TRADE_SUCCESS")
				{
					OnlinePay(order, array["trade_no"], Convert.ToDecimal(array["price"]));
				}

				/*
				#region 如果用了担保交易，并且当前状态为“等待发货”，则发货
				if (array["trade_status"] == "WAIT_SELLER_SEND_GOODS")
				{
					//TODO：要做什么，暂时不清楚
				}
				#endregion
				*/

				return "success";
				#endregion
			}
			else//默认认为是微信支付
			{
				WxPayApi.Notify notify = new WxPayApi.Notify();

				try
				{
					//获取数据
					SortedDictionary<string, object> array = notify.GetNotifyData();

					if (array["return_code"].ToString() == "FAIL")
					{
						//TODO：删除记录

						//返回已处理
						Manager.Log("CourseModule.Bll.Order - OnlinePayNotify - 默认认为是微信支付 - 1", "通知支付失败：" + array["return_msg"], Lang);
						return notify.BuildSuccess();
					}

					#region 获取资金
					Dictionary<string, object> order = Dal.Get(new Guid(array["out_trade_no"].ToString()));
					if (order == null)
					{
						#region 调试
						//File.AppendAllText(logFile, "\r\nNo record!");
						#endregion

						throw new Exception("out_trade_no没有对应的记录！");
					}
					#endregion

					#region 获取支付方式
					Dictionary<string, object> payment = null;
					using (SystemModule.IPayment paymentBll = (SystemModule.IPayment)Manager.CreateObject("Payment", 0, Lang, false))
					{
						payment = paymentBll.Get((Guid)order[Alias.Order.PaymentID]);
					}
					if (payment == null)
					{
						#region 调试
						//File.AppendAllText(logFile, "\r\nNo payment!");
						#endregion

						throw new Exception("支付对象未能获取！");
					}

					Dictionary<string, string> config = new Dictionary<string, string>();
					config["APPID"] = payment[SystemModule.Alias.Payment.AccountName].ToString();
					config["MCHID"] = payment[SystemModule.Alias.Payment.PartnerID].ToString();
					config["KEY"] = payment[SystemModule.Alias.Payment.Key].ToString();
					config["APPSECRET"] = payment[SystemModule.Alias.Payment.Account].ToString();
					#endregion

					#region 验证数据
					notify.Verify(config, array);
					#endregion

					#region 处理订单状态
					OnlinePay(order, array["transaction_id"].ToString(), Convert.ToDecimal(array["total_fee"]) / 100);
					#endregion

					#region debug
					/*
					string resultString = "";
					foreach (KeyValuePair<string, object> kvp in array)
					{
						if (resultString != "")
							resultString += "\r\n";
						resultString += kvp.Key + "=" + kvp.Value;
					}
					File.AppendAllText(Manager.MapPath("/log.txt"), "\r\n\r\n=============================================\r\n支付成功\r\n=============================================\r\n" + resultString + "\r\n");
					*/
					#endregion

					//返回成功
					return notify.BuildSuccess();
				}
				catch (Exception exp)
				{
					Manager.Log("GoodsModule.Bll.Order - OnlinePayNotify - 默认认为是微信支付 - 2", exp.ToString(), Lang);
					//File.AppendAllText(Manager.MapPath("/log.txt"), "\r\n\r\n=============================================\r\n" + exp.ToString() + "\r\n=============================================\r\n\r\n");
					return notify.BuildFail(exp.Message);
				}
			}
		}
		private bool OnlinePay(Dictionary<string, object> order, String tradeNo, Decimal amount)
		{
			if (Convert.ToInt32(order[Alias.Order.IsPayed]) > 0)
				return false;

			decimal sum = Convert.ToDecimal(order[Alias.Order.Sum]);
			if (sum != amount)
			{
				Manager.Log("CourseModule - Order - OnlinePay", "金额不相符。Sum=" + sum + "，Amount=" + amount, Lang);
				return false;
			}

			DateTime now = DateTime.Now;

			Dictionary<string, object> changes = new Dictionary<string, object>();
			changes[Alias.Order.PayTime] = now;
			changes[Alias.Order.TradeNo] = tradeNo;
			changes[Alias.Order.NotifyTime] = DateTime.Now;
			changes[Alias.Order.IsPayed] = 2;
			changes[Alias.Order.DeliverTime] = now;
			changes[Alias.Order.IsDelivered] = 2;

			int timeAmount = Convert.ToInt32(order[Alias.Order.TimeAmount]);
			switch (order[Alias.Order.TimeUnit].ToString())
			{
				case "MONTH":
					changes[Alias.Order.ExpiredTime] = now.AddMonths(timeAmount);
					break;
				case "SEASON":
					changes[Alias.Order.ExpiredTime] = now.AddMonths(3 * timeAmount);
					break;
				case "HAFE_YEAR":
					changes[Alias.Order.ExpiredTime] = now.AddMonths(6 * timeAmount);
					break;
				case "YEAR":
					changes[Alias.Order.ExpiredTime] = now.AddYears(timeAmount);
					break;
			}

			Dal.CheckRight = false;
			Dal.Modify((int)order[Alias.Order.InnerID], changes);

			//支付后处理
			OnAfterPay(order);

			//发货后处理
			OnAfterDeliver(order);

			return true;
		}

		private void OnAfterPay(Dictionary<string, object> order)
		{
			DataRow[] rows = Manager.Instances.Select(AliCMS.SystemModule.Alias.Module.Namespace + "='AliCMS.UserModule'");
			int userInstanceId = Convert.ToInt32(rows[0][AliCMS.SystemModule.Alias.Instance.InnerID]);

			//debug
			//Manager.Log("OnAfterPay - 代理分提成", "1", Lang);

			#region 如果有代理，则分提成
			if (!Convert.IsDBNull(order[Alias.Order.DistributerID]) && Convert.ToBoolean(order[Alias.Order.DistributerIsAgent]))
			{

				//debug
				//Manager.Log("OnAfterPay - 代理分提成", "2", Lang);

				Decimal agentCommision = Convert.ToDecimal(order[Alias.Order.AgentCommision]);
				if (agentCommision > 0)
				{
					using (UserModule.User.IMoney userMoneyBll = (UserModule.User.IMoney)Manager.CreateObject("User.Money", userInstanceId, Lang, false))
					{
						rows = Manager.Instances.Select(SystemModule.Alias.Instance.InnerID + "=" + InstanceID);
						object instanceId = rows[0][SystemModule.Alias.Instance.ID];

						Dictionary<string, object> userMoney = new Dictionary<string, object>();
						userMoney[UserModule.Alias.User.Money.UserID] = order[Alias.Order.DistributerID];
						userMoney[UserModule.Alias.User.Money.Title] = Lang == "UYG" ? "دەرسلىك سېتىۋىلىش - ۋاكالەتچى پايدىسى":"购买课程 - 代理佣金";
						userMoney[UserModule.Alias.User.Money.Amount] = agentCommision;
						userMoney[UserModule.Alias.User.Money.Time] = DateTime.Now;
						userMoney[UserModule.Alias.User.Money.Type] = "ALICOURSE_ORDER_BUY_AGENT_COMMISION";
						userMoney[UserModule.Alias.User.Money.OrderID] = order[Alias.Order.ID];
						userMoney[UserModule.Alias.User.Money.OrderNo] = order[Alias.Order.No];
						userMoney[UserModule.Alias.User.Money.OrderInstanceID] = instanceId;
						userMoneyBll.Add(userMoney);
					}

					//debug
					//Manager.Log("OnAfterPay - 代理分提成", "3", Lang);


					#region 通过公众号通知
					#region 接收者的OpenID
					string toUser;
					Dictionary<string, object> user;
					using (UserModule.IUser bll = (UserModule.IUser)Manager.CreateObject("User", userInstanceId, Lang, false))
					{
						user = bll.Get(order[Alias.Order.DistributerID]);
						if (user == null)
						{
							Manager.Log("CourseModule.Bll.Order - OnAfterPay - 获取通知接收者的OpenID - 1", "msg：接收者没有找到\r\nuserId：" + order[Alias.Order.DistributerID], Lang);
							return;
						}
						toUser = user[AliCMS.UserModule.Alias.User.WxppOpenID].ToString();

						if (String.IsNullOrEmpty(toUser))
						{
							Manager.Log("CourseModule.Bll.Order - OnAfterPay - 获取通知接收者的OpenID - 2", "msg：接收者没有绑定微信\r\nuserName：" + user[AliCMS.UserModule.Alias.User.Name] + "\r\nuserId：" + order[Alias.Order.DistributerID], Lang);
							return;
						}
					}
					#endregion

					#region 发送消息
					StringBuilder msg = new StringBuilder();
					msg.Append("{");
					msg.Append("\"touser\":\"" + toUser + "\",");
					msg.Append("\"template_id\":\"" + _templateId + "\",");
					msg.Append("\"url\":\"" + Manager.Site[AliCMS.SystemModule.Alias.InstanceConfig.Domain] + "\",");
					msg.Append("\"data\":");
					msg.Append("{");
					msg.Append("\"thing4\":{\"value\":\"" + order[Alias.Order.CourseName] + "\"},");
					msg.Append("\"amount5\":{\"value\":\"" + order[Alias.Order.Sum] + "\"},");
					msg.Append("\"thing8\":{\"value\":\"" + agentCommision + "\"}");
					msg.Append("}");
					msg.Append("}");
					SendWxppTemplateMsg(msg.ToString());
					#endregion

					#endregion

					//debug
					//Manager.Log("OnAfterPay - 代理分提成", "4", Lang);

				}
			}
			#endregion

			#region 如果有教师，则分提成
			if (!Convert.IsDBNull(order[Alias.Order.TeacherID]) && Convert.ToDecimal(order[Alias.Order.TeacherCommision]) > 0)
			{
				using (IDbObject bll = (IDbObject)Manager.CreateObject("Teacher", InstanceID, Lang, false))
				{
					Dictionary<string, object> teacher = bll.Get(order[Alias.Order.TeacherID]);
					if (!Convert.IsDBNull(teacher[Alias.Teacher.UserID]))
					{
						using (UserModule.User.IMoney userMoneyBll = (UserModule.User.IMoney)Manager.CreateObject("User.Money", userInstanceId, Lang, false))
						{
							rows = Manager.Instances.Select(SystemModule.Alias.Instance.InnerID + "=" + InstanceID);
							object instanceId = rows[0][SystemModule.Alias.Instance.ID];

							Dictionary<string, object> userMoney = new Dictionary<string, object>();
							userMoney[UserModule.Alias.User.Money.UserID] = order[Alias.Order.DistributerID];
							userMoney[UserModule.Alias.User.Money.Title] = Lang == "UYG" ? "دەرسلىك سېتىش - ئوقۇتقۇچى پايدىسى" : "课程销售 - 教师佣金";
							userMoney[UserModule.Alias.User.Money.Amount] = order[Alias.Order.TeacherCommision];
							userMoney[UserModule.Alias.User.Money.Time] = DateTime.Now;
							userMoney[UserModule.Alias.User.Money.Type] = "ALICOURSE_ORDER_BUY_TEACHER_COMMISION";
							userMoney[UserModule.Alias.User.Money.OrderID] = order[Alias.Order.ID];
							userMoney[UserModule.Alias.User.Money.OrderNo] = order[Alias.Order.No];
							userMoney[UserModule.Alias.User.Money.OrderInstanceID] = instanceId;
							userMoneyBll.Add(userMoney);
						}

						//TODO：通过公众号通知
					}
				}
			}
			#endregion

			#region 通过公众号发送“付款通知”
			//TODO：通过公众号通知
			/*
			int alibazaInstanceId = (int)Manager.Instances.Select(AliCMS.SystemModule.Alias.Module.Namespace + "='AliCMS.AlibazaModule'")[0][AliCMS.SystemModule.Alias.Instance.InnerID];
			using (IObject bll = (IObject)Manager.CreateObject("Notification", alibazaInstanceId, Lang, false))
			{
				bll.GetType().InvokeMember("Notify", BindingFlags.InvokeMethod, null, bll, new object[] { "NT_ALICOURSE_ORDER_PAY", Manager.BuildJson(order) });
			}
			*/
			#endregion
		}
		private void OnAfterDeliver(Dictionary<string, object> order)
		{
			#region 创建CourseStudy
			using (ICourseStudy bll = (ICourseStudy)Manager.CreateObject("CourseStudy", InstanceID, Lang, false))
			{
				Dictionary<string, object> item = new Dictionary<string, object>();
				item[Alias.CourseStudy.UserID] = order[Alias.Order.UserID];
				item[Alias.CourseStudy.CourseID] = order[Alias.Order.CourseID];
				item[Alias.CourseStudy.CourseName] = order[Alias.Order.CourseName];
				item[Alias.CourseStudy.CourseThumbnail] = order[Alias.Order.CourseThumbnail];
				bll.Add(item);

                #region 更新“正在学习数量”
                int count = bll.GetRecordCount(Alias.CourseStudy.CourseID + "=" + order[Alias.Order.CourseID]);
                using (ICourse courseBll = (ICourse)Manager.CreateObject("Course", InstanceID, Lang, false))
                {
                    int id = courseBll.GetInnerIDFromGuid((Guid)order[Alias.Order.CourseID]);

                    Dictionary<string, object> changes = new Dictionary<string, object>();
                    changes[Alias.Course.SaleCount] = count;
                    courseBll.Modify(id, changes);
                }
                #endregion
            }
            #endregion
        }
		private void OnAfterRefund(Dictionary<string, object> order)
        {
			DataRow[] rows = Manager.Instances.Select(AliCMS.SystemModule.Alias.Module.Namespace + "='AliCMS.UserModule'");
			int userInstanceId = Convert.ToInt32(rows[0][AliCMS.SystemModule.Alias.Instance.InnerID]);

			#region 退代理佣金
			if (!Convert.IsDBNull(order[Alias.Order.DistributerID]) && Convert.ToBoolean(order[Alias.Order.DistributerIsAgent]))
			{
				Decimal agentCommision = Convert.ToDecimal(order[Alias.Order.AgentCommision]);
				if (agentCommision > 0)
				{
					using (UserModule.User.IMoney userMoneyBll = (UserModule.User.IMoney)Manager.CreateObject("User.Money", userInstanceId, Lang, false))
					{
						rows = Manager.Instances.Select(SystemModule.Alias.Instance.InnerID + "=" + InstanceID);
						object instanceId = rows[0][SystemModule.Alias.Instance.ID];

						Dictionary<string, object> userMoney = new Dictionary<string, object>();
						userMoney[UserModule.Alias.User.Money.UserID] = order[Alias.Order.DistributerID];
						userMoney[UserModule.Alias.User.Money.Title] = Lang == "UYG" ? "دەرسلىك قايتۇرۇش - ۋاكالەتچى پايدىسى" : "课程退款 - 代理佣金";
						userMoney[UserModule.Alias.User.Money.Amount] = -agentCommision;
						userMoney[UserModule.Alias.User.Money.Time] = DateTime.Now;
						userMoney[UserModule.Alias.User.Money.Type] = "ALICOURSE_ORDER_REFUND_AGENT_COMMISION";
						userMoney[UserModule.Alias.User.Money.OrderID] = order[Alias.Order.ID];
						userMoney[UserModule.Alias.User.Money.OrderNo] = order[Alias.Order.No];
						userMoney[UserModule.Alias.User.Money.OrderInstanceID] = instanceId;
						userMoneyBll.Add(userMoney);
					}
				}
			}
			#endregion

			#region 退教师佣金
			if (!Convert.IsDBNull(order[Alias.Order.TeacherID]) && Convert.ToDecimal(order[Alias.Order.TeacherCommision]) > 0)
			{
				using (IDbObject bll = (IDbObject)Manager.CreateObject("Teacher", InstanceID, Lang, false))
				{
					Dictionary<string, object> teacher = bll.Get(order[Alias.Order.TeacherID]);
					if (!Convert.IsDBNull(teacher[Alias.Teacher.UserID]))
					{
						using (UserModule.User.IMoney userMoneyBll = (UserModule.User.IMoney)Manager.CreateObject("User.Money", userInstanceId, Lang, false))
						{
							rows = Manager.Instances.Select(SystemModule.Alias.Instance.InnerID + "=" + InstanceID);
							object instanceId = rows[0][SystemModule.Alias.Instance.ID];

							Dictionary<string, object> userMoney = new Dictionary<string, object>();
							userMoney[UserModule.Alias.User.Money.UserID] = order[Alias.Order.DistributerID];
							userMoney[UserModule.Alias.User.Money.Title] = Lang == "UYG" ? "دەرسلىك قايتۇرۇش - ئوقۇتقۇچى پايدىسى" : "课程退款 - 教师佣金";
							userMoney[UserModule.Alias.User.Money.Amount] = -Convert.ToDecimal(order[Alias.Order.TeacherCommision]);
							userMoney[UserModule.Alias.User.Money.Time] = DateTime.Now;
							userMoney[UserModule.Alias.User.Money.Type] = "ALICOURSE_ORDER_REFUND_TEACHER_COMMISION";
							userMoney[UserModule.Alias.User.Money.OrderID] = order[Alias.Order.ID];
							userMoney[UserModule.Alias.User.Money.OrderNo] = order[Alias.Order.No];
							userMoney[UserModule.Alias.User.Money.OrderInstanceID] = instanceId;
							userMoneyBll.Add(userMoney);
						}
					}
				}
			}
			#endregion
		}
		/*
		private void UpdateSaleCount(Dictionary<string, object> order)
		{
			using (ICourse bll = (ICourse)Manager.CreateObject("Course", InstanceID, Lang, false))
			{
				Dictionary<string, object> course = bll.Get(order[Alias.Order.CourseID]);

				Dictionary<string, object> changes = new Dictionary<string, object>();
				changes[Alias.Course.SaleCount] = (int)course[Alias.Course.SaleCount] + 1;
				bll.Modify((int)course[Alias.Course.InnerID], changes);
			}
		}
		*/

		#region 统计
		public string Stat(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Stat(data);
        }
        public string StatHourly(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.StatHourly(data);
        }
        public string StatDaily(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.StatDaily(data);
        }
        public string StatMonthly(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.StatMonthly(data);
        }
        #endregion

        #region 教师统计
        public string Teacher_StatOne(Guid teacherId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Teacher_StatOne(teacherId, data);
        }
        public string Teacher_StatAll(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"].ToString());
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"].ToString());
            }

            return Dal.Teacher_StatAll(data);
        }
        public string Teacher_StatHourly(Guid teacherId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Teacher_StatHourly(teacherId, data);
        }
        public string Teacher_StatDaily(Guid teacherId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Teacher_StatDaily(teacherId, data);
        }
        public string Teacher_StatMonthly(Guid teacherId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Teacher_StatMonthly(teacherId, data);
        }
        #endregion

        #region 课程统计
        public string Course_StatOne(Guid courseId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Course_StatOne(courseId, data);
        }
        public string Course_StatAll(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"].ToString());
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"].ToString());
            }

            return Dal.Course_StatAll(data);
        }
        public string Course_StatHourly(Guid courseId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Course_StatHourly(courseId, data);
        }
        public string Course_StatDaily(Guid courseId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Course_StatDaily(courseId, data);
        }
        public string Course_StatMonthly(Guid courseId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Course_StatMonthly(courseId, data);
        }
        #endregion

        #region 代理统计
        public string Agent_StatOne(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatOne(agentId, data);
        }
        public string Agent_StatAll(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"].ToString());
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"].ToString());
            }

            return Dal.Agent_StatAll(data);
        }
        public string Agent_StatHourly(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatHourly(agentId, data);
        }
        public string Agent_StatDaily(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatDaily(agentId, data);
        }
        public string Agent_StatMonthly(Guid agentId, Dictionary<string, object> data)
        {
            if (data.ContainsKey("Start"))
            {
                data["Start"] = Convert.ToDateTime(data["Start"]);
            }

            if (data.ContainsKey("End"))
            {
                data["End"] = Convert.ToDateTime(data["End"]);
            }

            return Dal.Agent_StatMonthly(agentId, data);
        }
		#endregion


		private void SendWxppTemplateMsg(string msg)
		{
			#region 获取AccessToken
			string appId = Manager.Site[AliCMS.SystemModule.Alias.InstanceConfig.WxppAppID + Lang];
			string appSecret = Manager.Site[AliCMS.SystemModule.Alias.InstanceConfig.WxppAppSecret + Lang];
			string accessToken = GetAccessToken(appId, appSecret);

			if (accessToken == null)
				return;
			#endregion

			HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken);
			request.Method = "POST";
			request.Timeout = 15 * 1000;
			request.ContentType = "application/json";
			byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg.ToString());
			request.ContentLength = buffer.Length;

			//往服务器写入数据
			Stream reqStream = request.GetRequestStream();
			reqStream.Write(buffer, 0, buffer.Length);
			reqStream.Close();

			//获取服务端返回
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
			String result = sr.ReadToEnd().Trim();
			sr.Close();

			JavaScriptSerializer serializer = new JavaScriptSerializer();
			Dictionary<string, object> json = serializer.DeserializeObject(result) as Dictionary<string, object>;
			if (Convert.ToInt32(json["errcode"]) != 0)
			{
				Manager.Log("CourseModule.Bll.Order - SendWxppTemplateMsg", "msg：模板消息发送失败\r\nerrcode：" + json["errcode"] + "\r\nerrmsg：" + json["errmsg"] + "\r\nmsg：" + msg.ToString(), Lang);
			}
		}
		public string GetAccessToken(string appId, string appSecret)
		{
			string dir = Manager.MapPath(Manager.GetDataPath(InstanceID, null)) + "access_token/";
			if (!Directory.Exists(dir))
				Directory.CreateDirectory(dir);

			int counter = 0;
			string lockFile = dir + appId + ".lock";
			while (File.Exists(lockFile))
			{
				if (counter == 5)
				{
					if (DateTime.Now.Subtract(File.GetCreationTime(lockFile)).Minutes > 5)
					{
						File.Delete(lockFile);
						break;
					}

					return null;
				}

				Thread.Sleep(1000);//等待一秒
				counter++;
			}

			string token = null;
			DateTime expiredTime = DateTime.MinValue;
			JavaScriptSerializer serializer = new JavaScriptSerializer();

			try
			{
				_logWriteLock.EnterWriteLock();

				//创建锁定文件
				File.Create(lockFile).Close();

				string path = dir + appId + ".txt";
				if (File.Exists(path))
				{
					Dictionary<string, object> json = serializer.DeserializeObject(File.ReadAllText(path)) as Dictionary<string, object>;
					token = json["token"].ToString();
					if (json["expiredTime"].ToString() != "")
						expiredTime = Convert.ToDateTime(json["expiredTime"].ToString());
				}

				if (String.IsNullOrEmpty(token) || expiredTime.Subtract(DateTime.Now).TotalMinutes < 5)
				{
					HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
					request.Timeout = 15 * 1000;
					HttpWebResponse response = (HttpWebResponse)request.GetResponse();
					StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
					String result = sr.ReadToEnd().Trim();
					sr.Close();

					Dictionary<string, object> json = serializer.DeserializeObject(result) as Dictionary<string, object>;
					if (!json.ContainsKey("access_token"))
					{
						Manager.Log("CourseModule - GetAccessToken - get", "appId：" + appId + "\r\nResult：" + result, Lang);
						return null;
					}

					token = json["access_token"].ToString();
					expiredTime = DateTime.Now.AddSeconds(Convert.ToInt32(json["expires_in"]));
					File.WriteAllText(path, "{\"token\":\"" + token + "\",\"expiredTime\":\"" + expiredTime.ToString() + "\"}");
				}
			}
			catch (Exception exp)
			{
				Manager.Log("CourseModule - GetAccessToken", "appId：" + appId + "\r\nException：" + exp.ToString(), Lang);
			}
			finally
			{
				File.Delete(lockFile);
				_logWriteLock.ExitWriteLock();
			}

			return token;
		}

		#region Fields
		public static ReaderWriterLockSlim _logWriteLock = new ReaderWriterLockSlim();
		public static string _templateId = "qsrPGNFuiZ4Br7NW8OpBBxFByBKjk-eLBcchshnvweQ";
		#endregion


		#region Properties
		private Dal.IOrder Dal
		{
			get { return (Dal.IOrder)DalBase; }
		}
		#endregion
	}
}
